﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ninject;
using Agro.Services;
using Agro.Models;
using Agro.Library;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System.Text;

namespace Agro.Web.Areas.DataManage.Controllers
{
    public class ReportSearchController : BaseController
    {
        //
        // GET: /DataManage/ReportSearch/
        [Inject]
        public IReportSearch ReportSearch { get; set; }

        public ActionResult Index(string reportid)
        {
            ViewBag.ReportID = reportid;

            T_Report report = ReportSearch.GetReport(reportid);
            ViewBag.CYCLE = report.Report_Cycle;
            ViewBag.GetOrganizeNodesUrl = Url.Content("~/SystemManage/Organization/GetChildOrganizationNodes/");
            return View();
        }
        [HttpPost]
        public ActionResult Search()
        {
            string year = Request["year"].ToString();
            string yearend = Request["yearend"].ToString();
            string month1 = Request["month1"].ToString();
            string month2 = Request["month2"].ToString();
            string zb = Server.UrlDecode(Request["zb"].ToString());
            string wd = Server.UrlDecode(Request["wd"].ToString());
            string reportid = Request["reportid"].ToString();
            string dwid = Request["dwid"].ToString();
            string[] dwidarr = dwid.Split(',');
            string htmlcontent = string.Empty;
            T_Report report = ReportSearch.GetEntity<T_Report>(T_Report._.Report_ID == reportid);

            htmlcontent = htmlcontent + string.Format("<div style='MARGIN-RIGHT: auto; MARGIN-LEFT: auto;text-align:center;width:auto;height:auto; '><div style='width:auto;padding:10px;font-size:20px;font-weight:bold;'>{0}</div>", report.Report_Name);
            if (month1 == null || month1 == "null") month1 = "";
            if (month2 == null || month2 == "null") month2 = "";

            switch (report.Report_Cycle)
            {
                case "01":
                case "02":
                    for (int i = int.Parse(year); i <= int.Parse(yearend); i++)
                    {
                        //每个月，也要分开显示
                        for (int j = int.Parse(month1); j <= int.Parse(month2); j++)
                        {
                            htmlcontent = htmlcontent + ReportSearch.ReportCompute(reportid, i.ToString(), j.ToString(), j.ToString(), zb, wd, dwidarr);
                        }
                    }
                    break;
                case "03":
                    for (int i = int.Parse(year); i <= int.Parse(yearend); i++)
                    {

                        htmlcontent = htmlcontent + ReportSearch.ReportCompute(reportid, i.ToString(), month1, month2, zb, wd, dwidarr);
                    }
                    break;

            }
            htmlcontent = htmlcontent + "</div>";
            return Content(htmlcontent);
        }

        public ActionResult Export()
        {
            string year = Request["year"].ToString();
            string yearend = Request["yearend"].ToString();
            string month1 = Request["month1"].ToString();
            string month2 = Request["month2"].ToString();
            string zb = Server.UrlDecode(Request["zb"].ToString());
            string wd = Server.UrlDecode(Request["wd"].ToString());
            string reportid = Request["reportid"].ToString();
            string dwid = Request["dwid"].ToString();
            string[] dwidarr = dwid.Split(',');
            string htmlcontent = string.Empty;

            //计算指标和纬度的数量，用来在标题行，合并单元格
            string[] zbarr = zb.Remove(zb.Length - 1).Split(',');
            string[] wdarr = wd.Remove(wd.Length - 1).Split(',');
            int zbcount = zbarr.Length;
            int wdcount = wdarr.Length;

            //创建一个工作簿
            MemoryStream stream = new MemoryStream();
            NPOI.SS.UserModel.IWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet();
            T_Report report = ReportSearch.GetReport(reportid);

            //设置标题行的样式
            ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;//对齐方式
            cellStyle.VerticalAlignment = VerticalAlignment.CENTER;//垂直对齐方式
            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREEN.index;
            cellStyle.FillPattern = FillPatternType.SQUARES;
            cellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.GREEN.index;//单元格背景色为绿色，符合农业的色彩 
            
            //也可以一种字体，写一些公共属性，然后在下面需要时加特殊的
            IFont font = workbook.CreateFont();
            font.Color = NPOI.HSSF.Util.HSSFColor.WHITE.index; //设置字体为白色
            font.FontHeightInPoints = 18;
            font.FontName = "宋体";
            cellStyle.SetFont(font);

            //插报表标题
            IRow titler = sheet.CreateRow(0);
            titler.Height = 550;
            ICell icell1 = null;//大标题用
            icell1 = titler.CreateCell(0);
            icell1.CellStyle = cellStyle;
            icell1.SetCellValue(report.Report_Name);
            //合并单元格
            CellRangeAddress cellRangeAddress1 = new CellRangeAddress(0, 0, 0, zbcount * wdcount);
            sheet.AddMergedRegion(cellRangeAddress1);
            //设置合并后，单元格的边框
            //((NPOI.HSSF.UserModel.HSSFSheet)sheet).SetEnclosedBorderOfRegion(cellRangeAddress1, NPOI.SS.UserModel.BorderStyle.THIN, NPOI.HSSF.Util.HSSFColor.BLACK.index);
            
            


            if (month1 == null || month1 == "null") month1 = "";
            if (month2 == null || month2 == "null") month2 = "";


            switch (report.Report_Cycle)
            {
                case "01":
                case "02":
                    for (int i = int.Parse(year); i <= int.Parse(yearend); i++)
                    {
                        //每个月，也要分开显示
                        for (int j = int.Parse(month1); j <= int.Parse(month2); j++)
                        {
                            sheet = ReportSearch.ExportExcel(sheet, reportid, i.ToString(), j.ToString(), j.ToString(), zb, wd, dwidarr);
                        }
                    }
                    break;
                case "03":
                    for (int i = int.Parse(year); i <= int.Parse(yearend); i++)
                    {

                        sheet = ReportSearch.ExportExcel(sheet, reportid, i.ToString(), month1, month2, zb, wd, dwidarr);
                    }
                    break;
            }
            #region 列宽自适应
            int maxColumn=0;
            IRow row=null ;
            for (int i = 0; i <= sheet.LastRowNum; i++)
            {
                row= sheet.GetRow(i);
                if (row.PhysicalNumberOfCells > maxColumn)
                {
                    maxColumn = row.PhysicalNumberOfCells;
                }

            }

            for (int i = 0; i <= maxColumn; i++)
            {
                sheet.AutoSizeColumn(i);
            }
            //获取当前列的宽度，然后对比本列的长度，取最大值   
            for (int columnNum = 0; columnNum <= maxColumn; columnNum++)
            {
                int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
                for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
                {
                    IRow currentRow;
                    //当前行未被使用过   
                    if (sheet.GetRow(rowNum) == null)
                    {
                        currentRow = sheet.CreateRow(rowNum);
                    }
                    else
                    {
                        currentRow = sheet.GetRow(rowNum);
                    }

                    if (currentRow.GetCell(columnNum) != null)
                    {
                        ICell currentCell = currentRow.GetCell(columnNum);
                        int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                        if (columnWidth < length)
                        {
                            columnWidth = length;
                        }
                    }
                }
                sheet.SetColumnWidth(columnNum, columnWidth * 256);
            }  

            #endregion

            workbook.Write(stream);
            stream.Flush();
            stream.Position = 0;


            string filename = "";
            if (year != yearend)
                filename = report.Report_Name + year + month1 + month2 + "至" + yearend + month1 + month2;
            else
                filename = report.Report_Name + year + month1 + month2;

            //Response.Clear();
            //Response.ContentType = "application/octet-stream";
            ////通知浏览器下载文件而不是打开
            ////Content-Disposition参数：
            ////attachment --- 作为附件下载    
            ////inline --- 在线打开


            //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xls");
            //byte[] bytes = new byte[(int)stream.Length];
            //stream.Read(bytes, 0, bytes.Length);
            //stream.Close();
            //Response.BinaryWrite(bytes);
            //Response.Flush();
            //Response.End();


            return Excel(stream, HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));

        }
    }
}











